﻿package com.badibadi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import com.badibadi.fragment.IndexClub0Fragment;
import com.badibadi.fragment.IndexClub0_1Fragment;
import com.badibadi.fragment.IndexClub1Fragment;
import com.badibadi.fragment.IndexClub1_1Fragment;
import com.badibadi.fragment.IndexClub2Fragment;
import com.badibadi.fragment.IndexClub2_1Fragment;
import com.badibadi.fragment.IndexClub3Fragment;
import com.badibadi.fragment.IndexClub3_1Fragment;
import com.badibadi.infos.Activity_Overview_Model;
import com.badibadi.infos.Results;
import com.badibadi.mydatabase.MyDataBase;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Convert;
import com.badibadi.mytools.FriendsTool;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.SetToMapToList;
import com.badibadi.mytools.TabHostUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.Toast;

//index_btn
public class IndexActivity extends BaseActivity implements OnClickListener {// index_btn
	protected TabHost tabhost;

	private Button index_return;
	private Intent intent = null;

	private ImageView index_btn, cha_cha_btn;

	private ViewIndexHolder holder;
	private Bundle bun;
	private String temp_edit = "";
	/**
	 * 判断选择的是tabhost的第几项
	 */
	private int TabItem = 0;

	FragmentManager manager;

	private AutoCompleteTextView autocompleteTextview;

	private IndexClub0Fragment indexClubFragment;// 第0项
	private IndexClub0_1Fragment indexClub0_1Fragment;// 俱乐部搜索内容显示

	private IndexClub1Fragment indexClub1Fragment;
	private IndexClub1_1Fragment indexClub1_1Fragment;// 活动搜索内容显示

	private IndexClub2Fragment indexClub2Fragment;
	private IndexClub2_1Fragment indexClub2_1Fragment;// 用户搜索内容显示

	private IndexClub3Fragment indexClub3Fragment;
	private IndexClub3_1Fragment indexClub3_1Fragment;// 地域搜索内容显示

	private boolean isRun = true;
	private Results results;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(IndexActivity.this);
					Utils.showMessage(IndexActivity.this, getResources()
							.getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:
				try {
					Utils.ExitPrgress(IndexActivity.this);
					Intent intent = new Intent(IndexActivity.this,
							CalendarBetweenActivity.class);
					intent.putExtra("搜索内容", autocompleteTextview.getText()
							.toString().trim());
					startActivity(intent);
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				try {
					Utils.ExitPrgress(IndexActivity.this);
					Utils.showMessage(IndexActivity.this, getResources()
							.getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.index);
		manager = getSupportFragmentManager();
		init();
		settingTabHost();
		initializeFragment("");
	}

	protected void initializeFragment(String d) {
		// TODO Auto-generated method stub
		ViewFragmentHolder viewHolder = new ViewFragmentHolder();
		if (d != null) {
			indexClubFragment = new IndexClub0Fragment();
			viewHolder.transaction.replace(R.id.index_layout,
					indexClubFragment, "indexClubFragment");
		} else {
			viewHolder.transaction.replace(R.id.index_layout,
					indexClub2Fragment, "indexClub2Fragment");
			TabItem = 2;
		}
		viewHolder.transaction.commit();
	}

	private void init() {
		Constants.overview_Models = new ArrayList<Activity_Overview_Model>();
		index_return = (Button) findViewById(R.id.index_return);
		index_return.setOnClickListener(IndexActivity.this);
		indexClub1Fragment = new IndexClub1Fragment();
		indexClub2_1Fragment = new IndexClub2_1Fragment();
		indexClub3_1Fragment = new IndexClub3_1Fragment();
		indexClub0_1Fragment = new IndexClub0_1Fragment();
		indexClub1_1Fragment = new IndexClub1_1Fragment();
		indexClub2Fragment = new IndexClub2Fragment();
		indexClub3Fragment = new IndexClub3Fragment();
		index_btn = (ImageView) this.findViewById(R.id.index_btn);
		index_btn.setOnClickListener(IndexActivity.this);
		cha_cha_btn = (ImageView) this.findViewById(R.id.cha_cha);
		cha_cha_btn.setOnClickListener(this);
		initAutoCompleteTextView();
	}

	/**
	 * 初始化自动完成文本框的适配 （和ViewIndexHolder一起就能用了）
	 */
	private void initAutoCompleteTextView() {
		// TODO Auto-generated method stub
		holder = new ViewIndexHolder();
		holder.cursor = holder.database.rawQuery(
				"select * from zidongwanchengwenben", null);
		autocompleteTextview = (AutoCompleteTextView) this
				.findViewById(R.id.index_autocomplete_text_view);
		// autoFinishtext=(AutoFinsishEdittext) autoFinishtext.LoadMsg();
		holder.cursor.moveToFirst();
		String s1 = holder.cursor.getString(0);
		//    
		holder.map.put(s1, s1);
		//    
		while (holder.cursor.moveToNext()) {
			String s2 = holder.cursor.getString(0);
			holder.map.put(s2, s2);
			//    
		}
		holder.list = Convert.mapTransitionList(holder.map);
		// 设置从第几个字开始提示
		autocompleteTextview.setThreshold(1);
		autocompleteTextview.setAdapter(new ArrayAdapter<String>(
				IndexActivity.this,
				android.R.layout.simple_dropdown_item_1line, holder.list));
		autocompleteTextview.addTextChangedListener(new TextWatcher() {
			// 这里是数据改变之后
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
//				   
//						+ "before=" + before + "/" + "count=" + count);
			}

			// 在数据改变之前 s为输入一个字符串之前 start 是 字符的个数，从0开始数
			// ，count为1时表示我上一步是加的字符串，count为0时表示我上一步是减的字符串
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
//				   
//						+ count);
			}

			// 数据改变之后
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				//    
//				   ("打印文字为:" + s + " 第几项:" + TabItem);
				temp_edit = s.toString();
				//    (d);
				if (s.length() > 0 && !"".equals(s) && TabItem == 0) {
					LoadingFragment(4);
				} else if (s.length() > 0 && !"".equals(s) && TabItem == 1) {
					if (!Constants.content_or_time) {
						LoadingFragment(5);
					} else {
						Utils.showMessage(IndexActivity.this, getResources()
								.getString(R.string.wx_txt_116));
					}
				} else if (s.length() > 0 && !"".equals(s) && TabItem == 2) {
					LoadingFragment(6);
				} else if (s.length() > 0 && !"".equals(s) && TabItem == 3) {
					LoadingFragment(7);
				}

				if (s.length() == 0 && TabItem == 4) {
					LoadingFragment(0);
				} else if (s.length() == 0 && TabItem == 5) {

					LoadingFragment(1);
				} else if (s.length() == 0 && TabItem == 6) {
					LoadingFragment(2);
				} else if (s.length() == 0 && TabItem == 7) {
					LoadingFragment(3);
				}
			}
		});
	}

	private void settingTabHost() {
		tabhost = (TabHost) findViewById(R.id.index_tabhost);
		tabhost.setup();
		tabhost.addTab(tabhost
				.newTabSpec("index one")
				.setIndicator(getResources().getString(R.string.club),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.index_tab1));
		tabhost.addTab(tabhost
				.newTabSpec("index two")
				.setIndicator(getResources().getString(R.string.activity),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.index_tab2));
		tabhost.addTab(tabhost
				.newTabSpec("index three")
				.setIndicator(getResources().getString(R.string.TheUser),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.index_tab3));
		tabhost.addTab(tabhost
				.newTabSpec("index four")
				.setIndicator(getResources().getString(R.string.Region),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.index_tab4));
		TabHostUtils.SetTabHost(this, tabhost);
		tabhost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

			@Override
			public void onTabChanged(String arg0) {
				// TODO Auto-generated method stub

				switch (tabhost.getCurrentTab()) {
				case 0:
					if (TabItem != 0 && temp_edit.length() <= 0) {
						LoadingFragment(0);
					} else {
						LoadingFragment(4);
					}
					// TabItem = 0;
					break;
				case 1:
					if (TabItem != 1 && temp_edit.length() <= 0) {
						LoadingFragment(1);
					} else {
						LoadingFragment(5);
					}
					// TabItem = 1;
					break;
				case 2:
					if (TabItem != 2 && temp_edit.length() <= 0) {
						LoadingFragment(2);
					} else {
						LoadingFragment(6);
					}
					// TabItem = 2;
					break;
				case 3:
					if (TabItem != 3 && temp_edit.length() <= 0) {
						LoadingFragment(3);
					} else {
						LoadingFragment(7);
					}
					// TabItem = 3;
					break;
				case 4:
					if (TabItem != 4 && temp_edit.length() > 0) {
						LoadingFragment(4);
					} else {
						LoadingFragment(0);
					}
				case 5:
					if (TabItem != 5 && temp_edit.length() > 0) {
						LoadingFragment(5);
					} else {
						LoadingFragment(1);
					}
					break;
				case 6:
					if (TabItem != 6 && temp_edit.length() > 0) {
						LoadingFragment(6);
					} else {
						LoadingFragment(2);
					}
					break;
				case 7:
					if (TabItem != 7 && temp_edit.length() > 0) {
						LoadingFragment(7);
					} else {
						LoadingFragment(3);
					}
					break;
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.index_return:
			IndexActivity.this.finish();
			overridePendingTransition(R.anim.slide_left2, R.anim.slide_right2);
			break;
		case R.id.index_btn:
			// autocompleteTextview
			if (TabItem == 1 || TabItem == 5) {
				if (Constants.content_or_time) {// 搜索时间模式
					if (temp_edit == null || temp_edit.length() == 0) {// 如果搜索内容为空才能进入搜索时间
						if (Utils.Judge_Time(Constants.START_TIME,
								Constants.END_TIME)) {
							li_activity_show();
						} else {
							Toast.makeText(getApplicationContext(),
									getResources().getString(R.string.l_xb1), 0)
									.show();
						}
					} else {// 搜索内容不为空则提示指定内容
						Utils.showMessage(IndexActivity.this, getResources()
								.getString(R.string.wx_txt_116));
					}
				} else {
					LoadingFragment(5);
				}
			}
			if (temp_edit.length() > 0 && !"".equals(temp_edit)
					&& (TabItem == 0 || TabItem == 4)) {
				LoadingFragment(4);
			} else if (temp_edit.length() > 0 && !"".equals(temp_edit)
					&& (TabItem == 2 || TabItem == 6)) {
				LoadingFragment(6);
			} else if (temp_edit.length() > 0 && !"".equals(temp_edit)
					&& (TabItem == 3 || TabItem == 7)) {
				LoadingFragment(7);
			}

			break;
		case R.id.cha_cha:
			autocompleteTextview.setText("");
			break;
		}
	}

	private void li_activity_show() {
		Utils.showPrgress(IndexActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("start", Constants.START_TIME);
				map.put("end", Constants.END_TIME);
				map.put("languageType", com.badibadi.mytools.Dialog
						.getSystemLanguageTypegrzx(IndexActivity.this));
				String t_content = Utils.sendRequest(map, Constants.BadiUrl
						+ "li_activity_show");
				if (t_content != null) {
//					   ("返回期间的活动是:" + t_content);
					results = Utils.checkResult_NNN(getApplicationContext(),
							t_content);
					if (results != null && !results.getRetmsg().equals("null")) {
						try {
							Constants.overview_Models = JSONUtils
									.getListByJsonString(results.getRetmsg(),
											Activity_Overview_Model.class);
							handler.sendEmptyMessage(2);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	/**
	 * 加载Fragment
	 * 
	 * @param item
	 *            根据item确定加载哪一个fragment
	 */
	private void LoadingFragment(int item) {
		// TODO Auto-generated method stub
		// ViewFragmentHolder vHolder = new ViewFragmentHolder();
		FragmentTransaction transaction = manager.beginTransaction();
		bun = new Bundle();
		switch (item) {
		case 0:
			indexClubFragment = new IndexClub0Fragment();
			transaction.replace(R.id.index_layout, indexClubFragment,
					"indexClubFragment");
			TabItem = 0;
			break;
		case 1:
			indexClub1Fragment = new IndexClub1Fragment();
			transaction.replace(R.id.index_layout, indexClub1Fragment,
					"indexClub1Fragment");
			TabItem = 1;
			break;
		case 2:
			indexClub2Fragment = new IndexClub2Fragment();
			transaction.replace(R.id.index_layout, indexClub2Fragment,
					"indexClub2Fragment");
			TabItem = 2;
			break;
		case 3:
			indexClub3Fragment = new IndexClub3Fragment();
			transaction.replace(R.id.index_layout, indexClub3Fragment,
					"indexClub3Fragment");
			TabItem = 3;
			break;
		case 4:
			indexClub0_1Fragment = new IndexClub0_1Fragment();
			bun.putString("editcontent", temp_edit);
			indexClub0_1Fragment.setArguments(bun);
			transaction.replace(R.id.index_layout, indexClub0_1Fragment,
					"indexClub0_1Fragment");
			TabItem = 4;
			break;
		case 5:
			indexClub1_1Fragment = new IndexClub1_1Fragment();
			bun.putString("editcontent", temp_edit);
			indexClub1_1Fragment.setArguments(bun);
			transaction.replace(R.id.index_layout, indexClub1_1Fragment,
					"indexClub1_1Fragment");
			TabItem = 5;
			break;
		case 6:
			indexClub2_1Fragment = new IndexClub2_1Fragment();
			bun.putString("editcontent", temp_edit);
			indexClub2_1Fragment.setArguments(bun);
			transaction.replace(R.id.index_layout, indexClub2_1Fragment,
					"indexClub2_1Fragment");
			TabItem = 6;
			break;
		case 7:
			indexClub3_1Fragment = new IndexClub3_1Fragment();
			bun.putString("editcontent", temp_edit);
			indexClub3_1Fragment.setArguments(bun);
			transaction.replace(R.id.index_layout, indexClub3_1Fragment,
					"indexClub3_1Fragment");
			TabItem = 7;
			break;

		}
		// vHolder.transaction.commit();
		transaction.commitAllowingStateLoss();
	}

	private class ViewIndexHolder {
		public SQLiteDatabase database;
		public Cursor cursor = null;
		public List<String> list;
		public Map<String, String> map;
		public MyDataBase mdb;

		public ViewIndexHolder() {
			mdb = new MyDataBase(IndexActivity.this);
			database = mdb.getWritableDatabase();
			map = new HashMap<String, String>();
			list = new ArrayList<String>();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (holder.database != null) {
			holder.database.close();
		}
		if (holder.mdb != null) {
			holder.mdb.close();
		}
	}

}
